#include "func.h"

// print usage
int usage(char *filename)
{
	printf("Usage: %s foo.txt\n", filename);

	return EXIT_OK;
}

int open_file(char *filename, FILE **pfp)
{
	*pfp = fopen(filename, "r");
	
	if (*pfp == NULL)
	{
		printf("failed to open file\n");
		return -1;
	}

	return EXIT_OK;
}
	
// get the max line number of file
int count_line(char *filename)
{
	FILE *fp = NULL;
	if (open_file(filename, &fp) !=0)
		return EXIT_ERR;

	char c;
	int nLine = 0;
	while(!feof(fp))
	{
		c = fgetc(fp);
		if (c == '\n') nLine++;
	}

	fclose(fp);

	return nLine;
}

// print blink ascii control code
int print_blink(int flag)
{
	if (flag)
		printf("[0;5m");

	return 0;
}

// print color code
int print_color(char *color)
{
	if (color == NULL)
		printf("");
	else
	if (strcmp(color, "red") == 0)
		printf("[31m");
	else
	if (strcmp(color, "green") == 0)
		printf("[32m");
	else
	if (strcmp(color, "yellow") == 0)
		printf("[33m");
	else
	if (strcmp(color, "blue") == 0)
		printf("[34m");
	else
	if (strcmp(color, "pink") == 0)
		printf("[35m");
	else
	if (strcmp(color, "cyan") == 0)
		printf("[36m");
	else
	if (strcmp(color, "white") == 0)
		printf("[37m");

	return EXIT_OK;
}

int print_ascii_end(int bBlink, char *pColor)
{
	if (bBlink || pColor)
		printf("[0m");
	printf("\n");

	return EXIT_OK;
}

int print_line(int bLinenum, int line, char *pLine)
{
	if (bLinenum)
		printf("%04d:%s", line+1, pLine);
	else
		printf("%s", pLine);

	return EXIT_OK;
}

// print help
int help(void)
{
	printf("Supported colors: red, green, yellow, blue, pink, cyan, white\n");
	printf("e.g.:\n");
	printf("\txline -c red foo.txt\n");
	printf("\txline -lc green foo.txt\n");

	return EXIT_OK;
}

// print version
int version(void)
{
	printf("xline. version:1.0.0\n");

	return EXIT_OK;
}

// print specified line
int show_line(int line, char *color, int blink, int linenum, char *filename)
{
	FILE *fp = NULL;
	if (open_file(filename, &fp) !=0)
		return EXIT_ERR;

	long lPosLineBegin = 0;
	long lPosLineEnd = 0;
	char c;
	int nCurrentLine = 0;

	while(!feof(fp))
	{
		// found the specified line
		if (nCurrentLine == line)
		{
			fseek(fp, lPosLineBegin, SEEK_SET);

			// find the end of the specified line
			while(!feof(fp))
			{
				c = fgetc(fp);
				if (c == '\n')
				{
					lPosLineEnd = ftell(fp);
					break;
				}
			}
			fseek(fp, lPosLineBegin, SEEK_SET);
			
			char *pLine = NULL;
			int len = lPosLineEnd - lPosLineBegin + 1;
			pLine = (char *)malloc(len);
			memset(pLine, 0, len);
			fgets(pLine, len - 1, fp);
			pLine[len-1] = '\0';
			print_blink(blink);
			print_color(color);
			print_line(linenum, line, pLine);
			print_ascii_end(blink, color);
			free(pLine);
				
			break;
		}

		c = fgetc(fp);

		// increase line indicator
		if (c == '\n')
		{
			nCurrentLine++;
			lPosLineBegin = ftell(fp);
		}

	}
	
	fclose(fp);

	return EXIT_OK;
}

